package com.yxq.mdt.app.modules.order.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.UmengShareHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.event.EventWxPay;
import com.yxq.mdt.app.modules.order.bean.EventOrderMsg;
import com.yxq.mdt.app.modules.order.bean.ExpressBean;
import com.yxq.mdt.app.modules.order.bean.OrderConfirmBean;
import com.yxq.mdt.app.modules.order.bean.OrderDetailBean;
import com.yxq.mdt.app.modules.order.bean.OrderListBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultBalanceBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultWxBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitResult;
import com.yxq.mdt.app.modules.order.model.OrderModel;
import com.yxq.mdt.app.modules.order.prestener.IOrderContract;
import com.yxq.mdt.app.modules.order.prestener.OrderPresenter;
import com.yxq.mdt.app.utils.WXUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 支付订单
 */
public class OrderPayActivity extends BaseActivity<OrderPresenter> implements IOrderContract.View {

    String orderId;
    String price;
    @BindView(R.id.order_pay_iv_wx)
    ImageView orderPayIvWx;
    @BindView(R.id.order_pay_layout_wx)
    RelativeLayout orderPayLayoutWx;
    @BindView(R.id.order_pay_iv_ali)
    ImageView orderPayIvAli;
    @BindView(R.id.order_pay_layout_ali)
    RelativeLayout orderPayLayoutAli;
    @BindView(R.id.order_pay_iv_balance)
    ImageView orderPayIvBalance;
    @BindView(R.id.order_pay_layout_balance)
    RelativeLayout orderPayLayoutBalance;
    @BindView(R.id.order_pay_btn_submit)
    Button orderPayBtnSubmit;
    int payMethod = 0;//支付方式
    IWXAPI api;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_pay;
    }

    @Override
    public void initView() {
        orderId = getIntent().getStringExtra("orderId");
        price = getIntent().getStringExtra("price");
        orderPayBtnSubmit.setText("微信支付￥" + price);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constant.WECHAT_ID);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new OrderPresenter(this, new OrderModel());
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.order_pay_layout_wx, R.id.order_pay_layout_ali, R.id.order_pay_layout_balance, R.id.order_pay_btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_pay_layout_wx:
                //微信
                setPayViewVisible(0);
                break;
            case R.id.order_pay_layout_ali:
                //支付宝
                setPayViewVisible(1);
                break;
            case R.id.order_pay_layout_balance:
                //余额
                setPayViewVisible(2);
                break;
            case R.id.order_pay_btn_submit:
                //支付
                pay();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 发起支付
     */
    private void pay() {

        switch (payMethod) {
            case 0://微信
                //判断是否安装微信
                if (!UmengShareHelper.isWeChatAvailable(mActivity)) {
                    ToastUtils.showShort("您尚未安装微信哦，请先安装微信");
                    return;
                }
                showLoadingDialog();
                mPresenter.payWX(orderId, "", "",getIntent().getBooleanExtra("gift", false));
                break;
            case 1://支付宝
                ToastUtils.showShort("暂未开通");
                break;
            case 2://余额
                showLoadingDialog();
                mPresenter.payBalance(orderId, "", "");
                break;
        }
    }

    private void setPayViewVisible(int i) {
        payMethod = i;
        switch (i) {
            case 0://微信
                orderPayIvWx.setVisibility(View.VISIBLE);
                orderPayIvAli.setVisibility(View.INVISIBLE);
                orderPayIvBalance.setVisibility(View.INVISIBLE);
                orderPayBtnSubmit.setText("微信支付" + price);
                break;
            case 1://支付宝
                orderPayIvWx.setVisibility(View.INVISIBLE);
                orderPayIvAli.setVisibility(View.VISIBLE);
                orderPayIvBalance.setVisibility(View.INVISIBLE);
                orderPayBtnSubmit.setText("支付宝支付" + price);
                break;
            case 2://余额
                orderPayIvWx.setVisibility(View.INVISIBLE);
                orderPayIvAli.setVisibility(View.INVISIBLE);
                orderPayIvBalance.setVisibility(View.VISIBLE);
                orderPayBtnSubmit.setText("余额支付" + price);
                break;

        }
    }

    @Override
    public void onLoadSuccess(OrderConfirmBean orderConfirmBean) {

    }

    @Override
    public void onLoadFailed(String err) {

    }

    @Override
    public void onLoadListSuccess(OrderListBean orderListBean) {

    }

    @Override
    public void onLoadListFailed(String err) {

    }

    @Override
    public void onSubmitSuccess(OrderSubmitResult orderSubmitResult) {

    }

    @Override
    public void onSubmitFailed(String err) {

    }

    @Override
    public void onPayBalanceSuccess(OrderPayResultBalanceBean orderPayResultBalanceBean) {
        hideLoadingDialog();
        ToastUtils.showShort("支付成功");
        Intent intent = new Intent(mActivity, OrderListTabActivity.class);
        intent.putExtra("gift", getIntent().getBooleanExtra("gift", false));
        intent.putExtra("orderId", orderId);
        intent.putExtra("price", price);
        startActivity(intent);
        finish();
    }

    @Override
    public void onPayBalanceFailed(String err) {
        hideLoadingDialog();
        ToastUtils.showShort(err);
    }

    @Override
    public void onPayWxSuccess(OrderPayResultWxBean orderPayResultWxBean) {
        hideLoadingDialog();
        String price = getIntent().getStringExtra("price");
        Double p = Double.parseDouble(price);
        if (0d == p) {
            //支付价格为0
            EventBus.getDefault().post(new EventWxPay(0));
            EventBus.getDefault().post(new EventWxPay(1));
            return;
        }
        //调起微信客户端支付
        invokeWxPay(orderPayResultWxBean);
    }

    private void invokeWxPay(OrderPayResultWxBean orderPayResultWxBean) {

        PayReq req = new PayReq();

        req.appId = Constant.WECHAT_ID;                         //微信开放平台审核通过的应用APPID
//        req.partnerId = orderPayResultWxBean.getRes().getMch_id();//微信支付分配的商户号
        req.partnerId = Constant.WECHAT_MCH_ID;//微信支付分配的商户号
        req.prepayId = orderPayResultWxBean.getRes().getPrepay_id();//预支付交易会话ID
        req.nonceStr = orderPayResultWxBean.getRes().getNonce_str();//随机字符串，不长于32位。
        req.timeStamp = orderPayResultWxBean.getTimeStamp();   //时间戳
        req.packageValue = "Sign=WXPay"; //扩展字段 暂填写固定值Sign=WXPay
        req.sign = WXUtil.genPayReq(req, orderPayResultWxBean); //二次签名
        api.sendReq(req);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventWxPay message) {
        switch (message.code) {
            case 0://支付成功
                ToastUtils.showShort("支付成功");
                EventBus.getDefault().post(new EventOrderMsg(1));
                EventBus.getDefault().post(new EventOrderMsg(2));
                Intent intent = new Intent(mActivity, OrderListTabActivity.class);
                intent.putExtra("gift", getIntent().getBooleanExtra("gift", false));
                intent.putExtra("orderId", orderId);
                intent.putExtra("price", price);
                startActivity(intent);
                finish();
                break;
            case -1://支付失败
                ToastUtils.showShort("支付失败");
                break;
            case -2://取消成功
                ToastUtils.showShort("取消支付");
                break;
        }
    }

    @Override
    public void onPayWxFailed(String err) {
        hideLoadingDialog();
        ToastUtils.showShort(err);
    }

    @Override
    public void onDetailSuccess(OrderDetailBean listBean) {

    }

    @Override
    public void onDetailFailed(String err) {

    }

    @Override
    public void onExpressSuccess(ExpressBean expressBean) {

    }

    @Override
    public void onExpressFailed(String err) {

    }
}
